# -*- coding: utf-8 -*-
# @Time : 2021/8/6 14:55
# @contact: 1325738369@qq.com
# @Author : tiannan
# @FileName: MinioObjectBase.py
# @Software: PyCharm
import io

from common.minio_config import minioClient
from minio.error import InvalidResponseError, S3Error
import os


class Object:

    def load_object(self, bucket_name, file_path):
        try:
            data = minioClient.get_object(bucket_name, file_path)
            bytes_data = bytes()
            for d in data.stream(32 * 1024):
                bytes_data += d
            return 'true', bytes_data
        except InvalidResponseError as err:
            return 'false', err

    def load_partial_object(self, bucket_name):
        try:
            data = minioClient.get_partial_object(bucket_name, '123.txt', 2, 8)
            with open('./load_files/123_new.txt', 'wb') as file_data:
                for d in data:
                    file_data.write(d)
            print("Sussess")  # 部分出现乱码
        except InvalidResponseError as err:
            print(err)

    def fget_object(self, bucket_name, filename):
        try:
            print(minioClient.fget_object(bucket_name, filename, 'test_new.jpg'))
        except InvalidResponseError as err:
            print(err)

    # 拷贝对象存储服务上的源对象到一个新对象
    # 注：该API支持的最大文件大小是5GB
    # 可通过copy_conditions参数设置copy条件
    # 经测试copy复制28M的文件需要663ms; 1.8G的压缩包需要53s
    def get_copy_object(self, bucket_name):
        try:
            copy_result = minioClient.copy_object(bucket_name, "123.jpg",
                                                  "/testfiles/123.jpg"
                                                  )
            print(copy_result)
        except InvalidResponseError as err:
            print(err)

    # 添加一个新的对象到对象存储服务
    """
    单个对象的最大大小限制在5TB。put_object在对象大于5MiB时，自动使用multiple parts方式上传。
    这样，当上传失败时，客户端只需要上传未成功的部分即可（类似断点上传）。
    上传的对象使用MD5SUM签名进行完整性验证。
    """

    def upload_object(self, bucket_name, filepath, file_data, file_size):
        # 放置一个具有默认内容类型的文件，成功后将打印服务器计算出的etag标识符
        try:
            minioClient.put_object(bucket_name, filepath,
                                   file_data, file_size)
            return 'true', 'ok'
        except InvalidResponseError as err:
            return 'false', err

    def fput_object(self, bucket_name, filepath):
        try:
            minioClient.fput_object(bucket_name, filepath, filename)
            print("Sussess")
        except InvalidResponseError as err:
            print(err)
        # try:
        #     print(minioClient.fput_object('pictures', 'long_lat.csv',
        #                                   './picture_files/long_lat.csv',
        #                                   content_type='application/csv'))
        #     print("Sussess")
        # except InvalidResponseError as err:
        #     print(err)

    def stat_object(self, bucket_name, filename):
        try:
            print(minioClient.stat_object(bucket_name, filename))
        except InvalidResponseError as err:
            print(err)

    def remove_object(self, bucket_name, file_path):
        try:
            try:
                minioClient.get_object(bucket_name, file_path)
                minioClient.remove_object(bucket_name, file_path)
                return 'true', 'ok'
            except:
                return 'false', '文件不存在'

        except InvalidResponseError as err:
            print(err)
            return 'err', err

    def remove_path_objects(self, bucket_name, prefix):
        try:
            objects = minioClient.list_objects(bucket_name, prefix=prefix,
                                               recursive=True)  # prefix用于过滤的对象名称前缀
            for obj in objects:
                file_path = str(obj.object_name)
                minioClient.remove_object(bucket_name, file_path)
            return 'true', 'ok'
        except InvalidResponseError as err:
            return 'false', err

    def remove_objects(self, bucket_name, del_obj_list):
        try:
            objects_to_delete = del_obj_list
            no_del_list = []
            for del_obj_path in objects_to_delete:
                try:
                    minioClient.remove_object(bucket_name, del_obj_path)
                except:
                    no_del_list.append(no_del_list)
            return 'true', no_del_list
        except InvalidResponseError as err:
            return 'false', err

    def remove_incomplete_upload(self, bucket_name):
        try:
            minioClient.remove_incomplete_upload(bucket_name, '123.jpg')
            print("Sussess")
        except InvalidResponseError as err:
            print(err)


if __name__ == '__main__':
    obj = Object()
    # Object().remove_incomplete_upload()recursive
    bucket_name = 'string-repair'
    # obj.upload_object(bucket_name, 'test_jpg.jpg')
    filename = 'test/redis.png'
    # obj.fput_object(bucket_name, filename)
    obj.remove_object(bucket_name, filename)
    obj.remove_path_objects(bucket_name, filename)
    # obj.fget_object(bucket_name, filename)
    # obj.stat_object(bucket_name,filename)
